package com.tarena.csmall.order.web.consumer;

import cn.tedu.mall.pojo.order.dto.OrderAddDTO;
import cn.tedu.mall.pojo.order.model.OmsOrder;
import cn.tedu.mall.pojo.seckill.dto.SeckillStockDTO;
import com.tarena.csmall.order.web.repository.OrderRepository;
import com.tarena.csmall.seckill.api.SeckillStockApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
    topic="order_delay_topic",consumerGroup = "order_delay_consumer_group",
    selectorExpression = "*")
@Slf4j
public class OrderDelayConsumer implements RocketMQListener<OrderAddDTO>{
    /**
     * 业务逻辑描述
     * 1. 检查携带的sn是否已经存在订单.订单状态是否是未支付 只关心未支付
     * 1.1 如果不是未支付状态,方法结束了
     * 1.2 如果是未支付,这张订单一定是超时未支付订单
     * 2. 关闭订单操作,和远程调用回退库存的操作
     */
    @Autowired
    private OrderRepository orderRepository;
    @DubboReference
    private SeckillStockApi seckillStockApi;
    @Override public void onMessage(OrderAddDTO message) {
        int count = orderRepository.countOrderSn(message.getSn());
        if (count==0) {
            log.error("延迟消息的订单不存在,请人为检查,sn:{}",message.getSn());
            return;
        }
        //查询订单,获取订单状态 只要不是0,不需要管理
        OmsOrder omsOrder=orderRepository.getOrder(message.getSn());
        if (omsOrder.getState()==0){
            //关闭订单
            orderRepository.clossOrder(message.getSn());
            //远程调用秒杀服务,将库存回退
            SeckillStockDTO seckillStockDTO=new SeckillStockDTO();
            seckillStockDTO.setSn(message.getSn());
            seckillStockDTO.setSkuId(message.getOrderItems().get(0).getSkuId());
            seckillStockDTO.setQuantity(message.getOrderItems().get(0).getQuantity());
            seckillStockApi.returnSeckillStock(seckillStockDTO);
        }
    }
}

